package com.test.antlr4.sql.visitor;

import com.test.antlr4.sql.bean.StatementStructure;
import com.test.antlr4.sql.core.SQLBaseVisitor;
import com.test.antlr4.sql.core.SQLParser;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 自定义sql解析访问器
 *
 * @author  2021/12/24
 */
public class LocalSQLBaseVisitor extends SQLBaseVisitor<StatementStructure> {
    private StatementStructure statementStructure ;
    private StatementStructure currentStatementStructure;
    private StatementStructure previouesStatementStructure;
    private int level = 0 ;

    @Override
    public StatementStructure visitColumn_name(SQLParser.Column_nameContext ctx) {
        List<String> fields = currentStatementStructure.getFields();
        System.out.println("column:" + ctx.getText());
        fields.add(ctx.getText());
        return statementStructure;
    }

    @Override
    public StatementStructure visitTableName(SQLParser.TableNameContext ctx) {
        List<String> sourceTables = currentStatementStructure.getSourceTables();
        System.out.println("table name:" + ctx.tmpName.getText());
        sourceTables.add(ctx.tmpName.getText());
        return statementStructure;
    }

    public void setStatementStructure(StatementStructure statementStructure) {
        this.statementStructure = statementStructure;
    }

    @Override
    public StatementStructure visitSelectStatement(SQLParser.SelectStatementContext ctx) {
        System.out.println("-------");
        if( Objects.isNull(previouesStatementStructure) && Objects.isNull(currentStatementStructure)
                && Objects.isNull(statementStructure)){
            statementStructure = new StatementStructure(new ArrayList<>() , new ArrayList<>());
            currentStatementStructure = statementStructure;
            level++;
        }else{
            previouesStatementStructure = currentStatementStructure;
            currentStatementStructure = new StatementStructure(new ArrayList<>() , new ArrayList<>());
            level++;
        }
        return super.visitSelectStatement(ctx);
    }

    public StatementStructure getStatementStructure() {
        return statementStructure;
    }
}
